package com.cjm.one.model.order.dto;

import com.cjm.one.model.custom.dto.UserStatsDTO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class OrderStatsDTO {
    // 顶部卡片数据
    private BigDecimal orderAmount;      // 订单金额（有效订单）
    private Long orderCount;          // 订单数量（已完成）
    private BigDecimal refundAmount;     // 退款金额（退款中）
    private Long refundOrderCount;    // 退款订单（待处理）
    
    // 环比增长率
    private BigDecimal amountGrowthRate;
    private BigDecimal countGrowthRate;
    private BigDecimal refundGrowthRate; // 退款金额（退款中）增长率
    private BigDecimal refundOrderGrowthRate; // 退款订单（待处理）增长率

    // 图表数据
    private List<OrderChartItem> chartData;
    // 增长率计算方法
    public void calculateGrowthRates(OrderStatsDTO previous) {
        this.amountGrowthRate = calculateRate(this.orderAmount, previous.orderAmount);
        this.countGrowthRate = calculateRate(this.orderCount, previous.orderCount);
        this.refundGrowthRate = calculateRate(this.refundAmount, previous.refundAmount);
        this.refundOrderGrowthRate = calculateRate(this.refundOrderCount ,previous.refundOrderCount);
    }
    private BigDecimal calculateRate(Long current, Long before) {
        if (before == null || before == 0) return BigDecimal.ZERO;
        return new BigDecimal((current - before) * 100.0 / before)
                .setScale(2, RoundingMode.HALF_UP);
    }
    private BigDecimal calculateRate(BigDecimal current, BigDecimal before) {
        // 参数校验
        if (current == null || before == null) {
            return BigDecimal.ZERO.setScale(2);
        }

        // 处理分母为0的情况
        if (before.compareTo(BigDecimal.ZERO) == 0) {
            return current.compareTo(BigDecimal.ZERO) > 0 ?
                    new BigDecimal("100.00") : BigDecimal.ZERO.setScale(2);
        }

        // 计算增长率（保留6位中间精度）
        BigDecimal difference = current.subtract(before);
        BigDecimal rate = difference
                .multiply(new BigDecimal("100"))
                .divide(before, 6, RoundingMode.HALF_UP);

        // 最终结果格式化
        return rate.setScale(2, RoundingMode.HALF_UP);
    }

    public OrderStatsDTO setOrderAmount(BigDecimal orderAmount) {
        this.orderAmount = orderAmount;
        return this;
    }
    public OrderStatsDTO setRefundOrderCount(Long refundOrderCount) {
        this.refundOrderCount = refundOrderCount;
        return this;
    }
    public OrderStatsDTO setOrderCount(Long orderCount) {
        this.orderCount = orderCount;
        return this;
    }
    public OrderStatsDTO setRefundAmount(BigDecimal refundAmount) {
        this.refundAmount = refundAmount;
        return this;
    }
}